package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.bussiness.platform.PlatformBussiness;
import com.yanqu.road.entity.platform.ServerMaxOnline;
import com.yanqu.road.entity.platform.ServerRegister;
import com.yanqu.road.entity.servercenter.AppKeyInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

@WebServlet(urlPatterns = "/platformQueryRegisterAndMaxOnline")
public class PlatformQueryRegisterAndMaxOnline extends BaseJsonHttpServlet {

	private static Logger logger = LogManager.getLogger(PlatformQueryRegisterAndMaxOnline.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("request platformQueryRegisterAndMaxOnline");
		HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
		JSONObject paramObj = httpJsonWebParam.getParamObj();
		int serverId;
		String date;
		String sign;
		try{
			serverId = paramObj.getIntValue("serverID");
			date = paramObj.getString("data");
			sign = paramObj.getString("sign");
			if(!DateHelper.isValidQueryDate(date)){
				logger.error("platformQueryRegisterAndMaxOnline date invalid,date:{}", date);
				sendResult(response, 0, "date invalid");
				return;
			}
		}catch (Exception e){
			logger.error("platformQueryRegisterAndMaxOnline argument error:" + e);
			sendResult(response, 0, "argument error");
			return;
		}
		try{
			long queryStartTime = DateHelper.getQueryDateTime(date);
			long queryEndTime = queryStartTime + DateHelper.HOUR_MILLIONS;
			if(serverId > 0) {
				getSingleServer(response, sign, date, serverId, queryStartTime, queryEndTime, paramObj);
			}else {
				getAllServer(response, sign, date, queryStartTime, queryEndTime, paramObj);
			}
		} catch (Exception e) {
			logger.error("platformQueryRegisterAndMaxOnline error:" + e);
			sendResult(response, 0, "other error");
		}
	}

	private void getSingleServer(HttpServletResponse response, String sign, String date, long serverId, long queryStartTime, long queryTime, JSONObject paramObj){
		if(WebServer.getInstance().isNeedSend() && ServerListMgr.isCnMergeServer(serverId)){
			// 转发消息到对应的服务器上
			String result = HttpHelper.doPostJson(ChannelConfig.LOGIN_SEND_URL + "platformBuyGoldToken", paramObj.toJSONString(), "UTF-8");
			sendMessage(response, result);
			return;
		}
		ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
		if (serverInfo == null) {
			logger.error("platformQueryRegisterAndMaxOnline no find serverId:{}", serverId);
			sendResult(response, 0, "serverId no exist");
			return;
		}
		AppKeyInfo appKeyInfo = AppKeyMgr.getAppKeyInfo(serverId);
		if(null == appKeyInfo){
			logger.error("platformQueryRegisterAndMaxOnline no find appKeyInfo serverId:{}", serverId);
			sendResult(response, 0, "appKeyInfo no exist");
			return;
		}
		SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
		if(!SignHelper.checkSign(paramMap, appKeyInfo.getAndroidAppSecret(), sign)){
			if(ServerListMgr.isCnMergeServer(serverId)){
				if(!SignHelper.checkSign(paramMap, ChannelConfig.APP_SECRET_CONFIG, sign)){
					logger.error("platformQueryRegisterAndMaxOnline sign error");
					sendResult(response, 0, "sign error");
					return;
				}
			}else {
				logger.error("platformQueryRegisterAndMaxOnline sign error");
				sendResult(response, 0, "sign error");
				return;
			}
		}

		int registerCount = 0;
		int maxCount = 0;
		ServerRegister serverRegister = PlatformBussiness.getServerRegister(serverId, queryStartTime, queryTime);
		ServerMaxOnline serverMaxOnline = PlatformBussiness.getServerMaxOnline(serverId, queryStartTime, queryTime);
		if(null != serverRegister){
			registerCount = serverRegister.getCount();
		}
		if(null != serverMaxOnline){
			maxCount = serverMaxOnline.getMaxCount();
		}
		JSONObject serverObj = new JSONObject();
		serverObj.put("newCreate", registerCount);
		serverObj.put("maxOnline", maxCount);
		JSONObject serverListObj = new JSONObject();
		serverListObj.put(serverId + "", serverObj);
		JSONObject dataObj = new JSONObject();
		dataObj.put("requestDate", date);
		dataObj.put("serverInfo", serverListObj);
		JSONObject resultObj = getResultObj(1, "success");
		resultObj.put("data", dataObj);
		sendMessage(response, resultObj.toJSONString());
	}

	private void getAllServer(HttpServletResponse response, String sign, String date, long queryStartTime, long queryTime, JSONObject paramObj){
		List<ServerInfo> serverInfoList = ServerListMgr.getOpenServerList();
		Map<Long, ServerRegister> serverRegisterMap = PlatformBussiness.getServerRegisterMap(queryStartTime, queryTime);
		Map<Long, ServerMaxOnline> serverMaxOnlineMap = PlatformBussiness.getServerMaxOnlineMap(queryStartTime, queryTime);
		JSONObject serverListObj = new JSONObject();
		ServerRegister serverRegister;
		ServerMaxOnline serverMaxOnline;
		for(ServerInfo serverInfo : serverInfoList){
			AppKeyInfo appKeyInfo = AppKeyMgr.getAppKeyInfo(serverInfo.getServerId());
			if(null == appKeyInfo){//没有签名信息，不列入
				continue;
			}
			SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
			if(!SignHelper.checkSign(paramMap, appKeyInfo.getAndroidAppSecret(), sign)){//签名校验错误，不列入
				if(ServerListMgr.isCnMergeServer(serverInfo.getServerId())){
					if(!SignHelper.checkSign(paramMap, ChannelConfig.APP_SECRET_CONFIG, sign)){
						continue;
					}
				}else {
					continue;
				}
			}
			int registerCount = 0;
			int maxCount = 0;
			serverRegister = serverRegisterMap.get(serverInfo.getServerId());
			if(null != serverRegister){
				registerCount = serverRegister.getCount();
			}
			serverMaxOnline = serverMaxOnlineMap.get(serverInfo.getServerId());
			if(null != serverMaxOnline){
				maxCount = serverMaxOnline.getMaxCount();
			}
			JSONObject serverObj = new JSONObject();
			serverObj.put("newCreate", registerCount);
			serverObj.put("maxOnline", maxCount);
			serverListObj.put(serverInfo.getServerId() + "", serverObj);
		}
		JSONObject dataObj = new JSONObject();
		dataObj.put("requestDate", date);
		dataObj.put("serverInfo", serverListObj);
		JSONObject resultObj = getResultObj(1, "success");
		resultObj.put("data", dataObj);
		sendMessage(response, resultObj.toJSONString());
	}
}
